package com.yzt.zhuju.utils;

import android.media.MediaPlayer;
import android.view.SurfaceHolder;

/**
 * author : bob
 * date   : 2023/2/22
 * desc   :
 */
public class VideoPlayerManager {

    private final MediaPlayer player;

    private IPlayVideo iplayVideo;

    public VideoPlayerManager() {
        player = new MediaPlayer();
    }

    public MediaPlayer getPlayer() {
        return player;
    }

    public void setupPlayback(String fileName) {
        setupPlayback(fileName, false);
    }

    public void setupPlayback(String fileName, boolean isLoop) {
        try {
            player.setDataSource(fileName);
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    iplayVideo.prepare();
                }
            });
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    iplayVideo.finish();
                }
            });
            player.setLooping(isLoop);
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDisplay(SurfaceHolder sf) {
        if (null != sf && null != player) {
            player.setDisplay(sf);
        }
    }

    public MediaPlayer getMediaPlyer() {
        return player;
    }

    public void startPlaying() {
        if (null != player) {
            player.start();
        }
    }

    public void pausePlaying() {
        player.pause();
    }

    public void seekTo(int pos) {
        if (pos < 0) {
            player.seekTo(0);
        } else if (pos > getDuration()) {
            player.seekTo(getDuration());
        } else {
            player.seekTo(pos);
        }
    }

    public void stopPlaying() {
        try {
            if (null != player && player.isPlaying()) {
                player.stop();
            }
        } catch (IllegalStateException ignored) {

        }
    }

    public boolean isPlaying() {
        if (null == player) {
            return false;
        }
        return player.isPlaying();
    }

    public int getCurrentPosition() {
        if (null == player) {
            return 0;
        }
        return player.getCurrentPosition();
    }

    public int getDuration() {
        if (null == player) {
            return 0;
        }
        return player.getDuration();
    }

    public void releasePlayer() {
        if (null != player) {
            try {
                player.release();
                setDisplay(null);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public interface IPlayVideo {

        void prepare();

        void finish();
    }

    public void setPlayVideo(IPlayVideo iplayVideo) {
        this.iplayVideo = iplayVideo;
    }

}
